package com.ncst.backend.service.impl;

import com.ncst.backend.common.PageResult;
import com.ncst.backend.domain.*;
import com.ncst.backend.domain.vo.RegisterPage;
import com.ncst.backend.mapper.DepartmentMapper;
import com.ncst.backend.mapper.EmployeeMapper;
import com.ncst.backend.mapper.MedicalRecordMapper;
import com.ncst.backend.mapper.RegisterMapper;
import com.ncst.backend.service.RegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 挂号服务实现类
 */
@Slf4j
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private MedicalRecordMapper medicalRecordMapper;
    @Override
    public Register getById(Integer id) {
        return registerMapper.selectById(id);
    }

    @Override
    public List<Register> getAll() {
        return registerMapper.selectAll();
    }

    @Override
    public List<Register> getByCondition(Register register) {
        return registerMapper.selectByCondition(register);
    }

    @Override
    public List<RegisterPage> getByPage(Integer pageNum, Integer pageSize) {
        Integer offset = (pageNum - 1) * pageSize;
        List<Register> registers = registerMapper.selectByPage(offset, pageSize);

        // 转换为RegisterPage列表并填充医生姓名和科室名称
        return convertToRegisterPageList(registers);
    }

    @Override
    public List<RegisterPage> getByPage(Integer pageNum, Integer pageSize, Register register, String startDate, String endDate) {
        Integer offset = (pageNum - 1) * pageSize;

        // 先根据条件查询所有符合条件的挂号记录
        List<Register> registers = registerMapper.selectByCondition(register);

        // 处理日期范围筛选
        if (startDate != null || endDate != null) {
            registers = registers.stream().filter(r -> {
                // 日期转换和筛选逻辑
                if (r.getVisitDate() == null) {
                    return false;
                }

                boolean afterStartDate = true;
                boolean beforeEndDate = true;

                // 开始日期筛选
                if (startDate != null && !startDate.isEmpty()) {
                    try {
                        // 简单的日期比较，实际应用中可能需要更复杂的日期解析
                        // 这里假设startDate是"yyyy-MM-dd"格式
                        String visitDateStr = r.getVisitDate().toString().split(" ")[0];
                        afterStartDate = visitDateStr.compareTo(startDate) >= 0;
                    } catch (Exception e) {
                        log.error("日期比较失败: {}", e.getMessage());
                    }
                }

                // 结束日期筛选
                if (endDate != null && !endDate.isEmpty()) {
                    try {
                        String visitDateStr = r.getVisitDate().toString().split(" ")[0];
                        beforeEndDate = visitDateStr.compareTo(endDate) <= 0;
                    } catch (Exception e) {
                        log.error("日期比较失败: {}", e.getMessage());
                    }
                }

                return afterStartDate && beforeEndDate;
            }).collect(Collectors.toList());
        }

        // 执行分页操作
        int startIndex = Math.min(offset, registers.size());
        int endIndex = Math.min(offset + pageSize, registers.size());
        List<Register> paginatedRegisters = registers.subList(startIndex, endIndex);

        // 转换为RegisterPage列表
        return convertToRegisterPageList(paginatedRegisters);
    }

    @Override
    public PageResult<RegisterPage> page(Integer pageNum, Integer pageSize, Register register, String startDate, String endDate) {
        // 复用条件分页逻辑，先取全部再内存过滤（后续可优化为 SQL 条件+limit）
        List<RegisterPage> all = getByPage(pageNum, pageSize, register, startDate, endDate); // 当前实现只返回当前页
        // 为了 total，需要单独获取符合条件的总数：沿用 selectByCondition + 日期过滤后 size
        List<Register> registers = registerMapper.selectByCondition(register);
        if (startDate != null || endDate != null) {
            registers = registers.stream().filter(r -> r.getVisitDate() != null).filter(r -> {
                String visitDateStr = r.getVisitDate().toString().split(" ")[0];
                boolean pass = true;
                if (startDate != null && !startDate.isEmpty()) pass &= visitDateStr.compareTo(startDate) >= 0;
                if (endDate != null && !endDate.isEmpty()) pass &= visitDateStr.compareTo(endDate) <= 0;
                return pass;
            }).collect(Collectors.toList());
        }
        long total = registers.size();
        return new PageResult<>(all, total, pageNum, pageSize);
    }

    /**
     * 将Register列表转换为RegisterPage列表并填充医生姓名和科室名称
     */
    private List<RegisterPage> convertToRegisterPageList(List<Register> registers) {
        return registers.stream().map(register -> {
            RegisterPage registerPage = new RegisterPage();
            // 复制基本属性
            registerPage.setId(register.getId());
            registerPage.setCaseNumber(register.getCaseNumber());
            registerPage.setRealName(register.getRealName());
            registerPage.setGender(register.getGender());
            registerPage.setCardNumber(register.getCardNumber());
            registerPage.setBirthday(register.getBirthday());
            registerPage.setAge(register.getAge());
            registerPage.setAgeType(register.getAgeType());
            registerPage.setHomeAddress(register.getHomeAddress());
            registerPage.setVisitDate(register.getVisitDate());
            registerPage.setNoon(register.getNoon());
            registerPage.setDeptmentId(register.getDeptmentId());
            registerPage.setEmployeeId(register.getEmployeeId());
            registerPage.setRegistLevelId(register.getRegistLevelId());
            registerPage.setSettleCategoryId(register.getSettleCategoryId());
            registerPage.setIsBook(register.getIsBook());
            registerPage.setRegistMethod(register.getRegistMethod());
            registerPage.setVisitState(register.getVisitState());
            registerPage.setRegistMoney(register.getRegistMoney());

            // 查询并设置医生姓名
            if (register.getEmployeeId() != null) {
                try {
                    Employee employee = employeeMapper.selectById(register.getEmployeeId());
                    if (employee != null) {
                        registerPage.setEmployeeName(employee.getRealname());
                    }
                } catch (Exception e) {
                    log.error("查询医生信息失败: {}", e.getMessage());
                    registerPage.setEmployeeName("未知医生");
                }
            }

            // 查询并设置科室名称
            if (register.getDeptmentId() != null) {
                try {
                    Department department = departmentMapper.selectById(register.getDeptmentId());
                    if (department != null) {
                        registerPage.setDeptmentName(department.getDeptName());
                    }
                } catch (Exception e) {
                    log.error("查询科室信息失败: {}", e.getMessage());
                    registerPage.setDeptmentName("未知科室");
                }
            }

            return registerPage;
        }).collect(Collectors.toList());
    }

    @Override
    public Long countAll() {
        return registerMapper.countAll();
    }

    @Override
    public Long countByCondition(Register register) {
        return registerMapper.countByCondition(register);
    }

    @Override
    public boolean save(Register register) {
        return registerMapper.insert(register) > 0;
    }

    @Override
    public boolean saveBatch(List<Register> list) {
        return registerMapper.insertBatch(list) > 0;
    }

    @Override
    public boolean updateById(Register register) {
        return registerMapper.updateById(register) > 0;
    }

    @Override
    public boolean removeById(Integer id) {
        return registerMapper.deleteById(id) > 0;
    }

    @Override
    public boolean removeByIds(List<Integer> ids) {
        return registerMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Map<String, Object> getTodayStats() {
        Map<String, Object> stats = new HashMap<>();
        try {
            // 获取当前日期字符串，格式为yyyy-MM-dd
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String today = dateFormat.format(new Date());

            // 创建查询条件，只查询今天的挂号记录
            Register register = new Register();
            List<Register> todayRegisters = registerMapper.selectByCondition(register)
                    .stream()
                    .filter(r -> {
                        // 过滤出今天的挂号记录
                        if (r.getVisitDate() == null) {
                            return false;
                        }
                        String visitDateStr = dateFormat.format(r.getVisitDate());
                        return visitDateStr.equals(today);
                    })
                    .collect(Collectors.toList());

            // 统计各类状态的患者数量
            long totalCount = todayRegisters.size();
            long registeredCount = todayRegisters.stream().filter(r -> r.getVisitState() == 1).count(); // 已挂号
            long consultingCount = todayRegisters.stream().filter(r -> r.getVisitState() == 2).count(); // 医生接诊
            long completedCount = todayRegisters.stream().filter(r -> r.getVisitState() == 3).count(); // 看诊结束
            long refundedCount = todayRegisters.stream().filter(r -> r.getVisitState() == 4).count(); // 已退号

            // 计算待接诊数量（已挂号但未接诊的数量）
            long pendingCount = registeredCount;

            // 将统计结果放入Map
            stats.put("today", today);
            stats.put("totalCount", totalCount);
            stats.put("pendingCount", pendingCount);
            stats.put("consultingCount", consultingCount);
            stats.put("completedCount", completedCount);
            stats.put("refundedCount", refundedCount);

        } catch (Exception e) {
            log.error("获取今日患者统计数据失败: {}", e.getMessage());
            // 出错时返回空的统计数据，避免影响前端展示
            stats.put("today", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            stats.put("totalCount", 0L);
            stats.put("pendingCount", 0L);
            stats.put("consultingCount", 0L);
            stats.put("completedCount", 0L);
            stats.put("refundedCount", 0L);
        }

        return stats;
    }

    @Override
    public List<MedicalRecord> getMedicalRecordByCaseNumberOrRealName(String caseNumber, String realName) {
        // 直接调用 mapper 中的模糊/条件查询（假设已存在对应方法）
        return medicalRecordMapper.selectByCaseNumberOrRealName(caseNumber, realName);
    }

    @Override
    public List<MedicalTechnology> getMedicalTechnologyByCaseNumberOrRealName(String caseNumber, String realName) {
        // 示例：如果 medicalRecordMapper 封装了跨表医技查询则调用，否则后续可独立到 MedicalTechnologyMapper
        log.info("查询医技项目，病历号: {}, 姓名: {}", caseNumber, realName);
        List<MedicalTechnology> medicalTechnologies = medicalRecordMapper.selectMedicalTechnologyByCaseNumberOrRealName(caseNumber, realName);
        log.info("查询到的医技项目: {}", medicalTechnologies);
        return medicalTechnologies;
    }

    @Override
    public Register getByCaseNumberOrRealName(String caseNumber, String realName) {
        Register register = new Register();
        register.setCaseNumber(caseNumber);
        register.setRealName(realName);
        List<Register> registers = registerMapper.selectByCondition(register);
        if (registers != null && !registers.isEmpty()) {
            return registers.get(0);
        }
        return null;
    }

    @Override
    public Integer ChargeSettle(List<Integer> items, Integer patientId, BigDecimal totalAmount) {
        return registerMapper.ChargeSettle(patientId);
    }

}
